package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdSensitiveMapper;
import com.heima.admin.service.AdSensitiveService;
import com.heima.common.exception.LogicException;
import com.heima.common.exception.ParamException;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.admin.dto.SensitiveDto;
import com.heima.model.admin.pojo.AdSensitive;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
@Slf4j
public class AdSensitiveServiceImpl extends ServiceImpl<AdSensitiveMapper, AdSensitive> implements AdSensitiveService {

    @Override
    public IPage list(SensitiveDto dto) {
        //2.模糊查询 + 分页
        IPage page = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<AdSensitive> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(dto.getName())) {
            lambdaQueryWrapper.like(AdSensitive::getSensitives, dto.getName());
        }

        return page(page, lambdaQueryWrapper);
    }

    @Override
    public void insert(AdSensitive wmSensitive) {

        //已存在的敏感词，不能保存
        AdSensitive sensitive = getOne(Wrappers.<AdSensitive>lambdaQuery().eq(AdSensitive::getSensitives, wmSensitive.getSensitives()));
        if (sensitive != null) {
            throw new LogicException(AppHttpCodeEnum.DATA_EXIST);
        }

        //2.保存
        wmSensitive.setCreatedTime(new Date());
        wmSensitive.setUpdatedTime(new Date());

        save(wmSensitive);
    }

    /**
     * 修改
     *
     * @param wmSensitive
     */
    @Override
    public void update(AdSensitive wmSensitive) {
        //1.检查参数
        if (null == wmSensitive || wmSensitive.getId() == null) {
            throw new ParamException(AppHttpCodeEnum.DATA_EXIST);
        }
        //2.修改
        updateById(wmSensitive);
    }

    /**
     * 删除
     *
     * @param id
     */
    @Override
    public void delete(Integer id) {
        //1.检查参数
        if (id == null) {
            throw new ParamException(AppHttpCodeEnum.DATA_EXIST);
        }
        //2.查询敏感词
        AdSensitive wmSensitive = getById(id);
        if (wmSensitive == null) {
            throw new LogicException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.删除
        removeById(id);
    }
}
